package com.homestead.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.homestead.domain.entity.BackUser;
import com.homestead.domain.mapper.BackUserMapper;
import com.homestead.domain.model.SignInIdentity;
import com.homestead.enums.CommonErrorCode;
import com.homestead.exception.UserException;
import com.homestead.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 登录校验
 * @author yhb
 */
@Service
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class UserServiceImpl extends ServiceImpl<BackUserMapper, BackUser> implements UserService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        BackUser backUser = new LambdaQueryChainWrapper<>(baseMapper).eq(BackUser::getUsername, username).one();
        if (backUser == null) {
            throw new UserException(CommonErrorCode.NAME_OR_PASSWORD_ERROR);
        }
        // 初始化登录认证对象
        SignInIdentity signInIdentity = new SignInIdentity();
        // 拷贝属性
        BeanUtils.copyProperties(backUser, signInIdentity);
        return signInIdentity;
    }

}
